<template>
  <div class="content-box-full role-box">
    <ContainerBox>
      <template #header>
        <el-form ref="searchFormRef" :model="searchForm" label-width="auto" inline>
          <el-form-item label="用户账号：" prop="username">
            <el-input v-model.number="searchForm.username" type="text" autocomplete="off" />
          </el-form-item>
          <!--          <el-form-item label="用户名称：" prop="name">-->
          <!--            <el-input v-model.number="searchForm.name" type="text" autocomplete="off" />-->
          <!--          </el-form-item>-->
          <el-form-item label="账号状态" prop="userStatus">
            <el-select class="inline-select" v-model="searchForm.userStatus">
              <el-option
                v-for="item in STATUS_LIST"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button v-permission="'sys:user:list'" type="primary" @click="fetchUserList"
              >查询
            </el-button>
            <el-button v-permission="'sys:user:save'" @click="openMenuDialog('add')"
              >新增</el-button
            >
          </el-form-item>
        </el-form>
      </template>
      <template #default>
        <el-table
          :data="tableData"
          :empty-text="isLoadingTable ? '加载中...' : '暂无数据'"
          class="table-box"
          height="100%"
          stripe
          fit
          border
          highlight-current-row
        >
          <el-table-column type="index" label="序号" align="center" width="80"></el-table-column>
          <el-table-column label="用户账号" align="center" min-width="120" prop="username">
          </el-table-column>
          <el-table-column label="用户名称" align="center" min-width="120" prop="name">
          </el-table-column>
          <el-table-column label="账号状态" align="center" min-width="60" prop="status">
            <template #default="{ row }">
              <el-tag size="small" v-if="row.status === 1">正常</el-tag>
              <el-tag size="small" v-else type="warning">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" min-width="100" prop="remark">
          </el-table-column>
          <el-table-column label="创建时间" align="center" min-width="120" prop="createTime">
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="120">
            <template #default="{ row }">
              <el-button
                v-permission="'sys:user:update'"
                @click="openMenuDialog('edit', row.userId)"
                >编辑</el-button
              >
              <el-button
                v-permission="'sys:user:delete'"
                :disabled="(row.username || '').toLowerCase() === 'admin'"
                @click="handleDelete(row)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <CommonPaging
          :total="tableTotal"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        ></CommonPaging>
      </template>
    </ContainerBox>
    <el-dialog
      class="common-el-dialog"
      lock-scroll
      top="10vh"
      v-model="addRoleDialog"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="800"
      @close="handleClose"
    >
      <el-form
        ref="userFormRef"
        :model="dataForm"
        :rules="roleRules"
        label-width="auto"
        status-icon
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户账号" prop="username">
              <el-input
                :disabled="dialogType === 'edit' && dataForm.username === 'admin'"
                v-model="dataForm.username"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名称" prop="name">
              <el-input v-model="dataForm.name" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="登录密码" prop="password">
              <el-input
                @input="checkPasswordStrength"
                type="password"
                show-password
                autocomplete="off"
                v-model="dataForm.password"
              >
                <template #append v-if="passwordState.strengthText">
                  <el-tag :type="passwordState.strengthClass"
                    >{{ passwordState.strengthText }}
                  </el-tag>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                type="password"
                show-password
                autocomplete="off"
                v-model="dataForm.confirmPassword"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="用户角色" prop="userRoles">
          <el-select v-model="dataForm.userRoles">
            <el-option
              :value="item.roleId"
              v-for="item in roleSelectList"
              :key="item.roleId"
              :label="item.roleName"
            />
          </el-select>
          <!--          <el-checkbox-group :max="1" v-model="dataForm.userRoles">-->
          <!--            <el-checkbox v-for="item in roleSelectList" :key="item.roleId" :label="item.roleName"-->
          <!--                         :value="item.roleId"></el-checkbox>-->
          <!--          </el-checkbox-group>-->
        </el-form-item>
        <el-form-item label="关联食堂" prop="canteenCheckNames">
          <el-popover
            popper-class="form-item-popper"
            ref="menuListPopover"
            placement="bottom-start"
            trigger="click"
          >
            <el-tree
              class="common-el-tree hx-scroll"
              :data="canteenTreeData"
              node-key="id"
              ref="canteenTreeRef"
              :default-expand-all="true"
              :highlight-current="true"
              :props="defaultProps"
              @check-change="checkChange"
              show-checkbox
              :expand-on-click-node="false"
            >
            </el-tree>
            <template #reference>
              <el-input
                v-model="dataForm.canteenCheckNames"
                readonly
                placeholder="点击勾选关联食堂"
                class="menu-list__input"
              ></el-input>
            </template>
          </el-popover>
        </el-form-item>
        <el-form-item label="薪资范围" prop="salaryRange">
          <el-select collapse-tags multiple v-model="dataForm.salaryRange" placeholder="薪资范围">
            <el-option
              v-for="item in hcmPayGroupEntities"
              :key="item.id"
              :value="item.code"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="dutyStatus">
          <el-radio-group v-model="dataForm.dutyStatus">
            <el-radio label="禁用" :value="0"></el-radio>
            <el-radio label="正常" :value="1"></el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addRoleDialog = false">取消</el-button>
          <el-button type="primary" @click="handleFormSubmit"> 确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from 'vue'
import ContainerBox from '@/components/base/ContainerBox.vue'
import CommonPaging from '@/components/base/CommonPaging.vue'
import accessApi from '@/api/accessApi.js'
import message from '@/utils/elMessage.js'
import { usePublicStore } from '@/stores/publicInfo.js'
import { STATUS_LIST } from '@/utils/systemConfig.js'
import { encryptPassword } from '@/utils/cryptoUtils.js'

const publicStore = usePublicStore()
const canteenTreeData = computed(() => publicStore.sysAreaEntityList)
const hcmPayGroupEntities = computed(() => publicStore.hcmPayGroupEntities)
onMounted(() => {
  fetchUserList()
})
const searchFormRef = ref(null)
const searchForm = ref({
  username: '', //用户账号
  name: '', //用户名称
  userStatus: 1, //用户状态
})

//新增-用户角色selectList
function getRoleSelect() {
  return new Promise((resolve) => {
    const params = {
      t: Date.now(),
    }
    accessApi.getRoleSelect(params).then((res) => {
      if (res.code === 0) {
        resolve(res.list || [])
      } else {
        resolve([])
      }
    })
  })
}

//通用打开新增、编辑弹窗方法
async function openMenuDialog(type, userId) {
  //获取弹窗中角色数据
  roleSelectList.value = await getRoleSelect()
  // //获取食堂组织
  // canteenTreeData.value = await fetchUserCanteenTree()
  //编辑反查
  if (type !== 'add' && userId) {
    await checkInfo(userId)
  }
  dialogType.value = type
  addRoleDialog.value = true
  await nextTick(() => {
    canteenTreeRef.value.setCheckedKeys(dataForm.value.areaList || [])
  })
}

//删除
function handleDelete(row) {
  if (row.userId) {
    message.confirm('您是否确定要删除该用户?', '提示').then(() => {
      accessApi
        .deleteUsers([row.userId])
        .then((res) => {
          if (res.code === 0) {
            message.success(res.msg)
            fetchUserList()
          } else {
            message.warning(res.msg)
          }
        })
        .catch((error) => {
          console.error(error.messages)
        })
    })
  }
}

//反查当前用户信息
function checkInfo(id) {
  return new Promise((resolve) => {
    accessApi
      .checkUserInfo(id, {
        t: Date.now(),
      })
      .then((res) => {
        if (res.code === 0) {
          nextTick(() => {
            const data = res.user || {}
            dataForm.value.userId = id
            dataForm.value.username = data.username || ''
            dataForm.value.name = data.name || ''
            dataForm.value.salaryRange = data.companyList || []
            dataForm.value.areaList = data.areaList || [] //用于回显勾选
            dataForm.value.userRoles = Array.isArray(data.roleIdList) ? data.roleIdList[0] : ''
            dataForm.value.dutyStatus = data.status || 1
            resolve()
          })
        } else {
          message.warning(res.msg)
        }
      })
  })
}

const isLoadingTable = ref(false)
const tableData = ref([])
const tableTotal = ref(0)

//查询用户list
function fetchUserList() {
  isLoadingTable.value = true
  tableData.value = []
  tableTotal.value = 0
  const params = {
    t: Date.now(),
    page: pageNum.value,
    limit: pageSize.value,
    username: searchForm.value.username,
    name: searchForm.value.name,
    status: searchForm.value.userStatus,
  }
  accessApi
    .getUserList(params)
    .then((res) => {
      if (res.code === 0) {
        tableData.value = res.page?.list || []
        tableTotal.value = res.page?.totalCount || 0
      } else {
        message.warning(res.message)
      }
    })
    .catch((error) => {
      console.error(error)
    })
    .finally(() => {
      isLoadingTable.value = false
    })
}

const pageSize = ref(10)
const pageNum = ref(1)

function handlePageChange(num) {
  pageNum.value = num
  fetchUserList()
}

function handleSizeChange(size) {
  pageSize.value = size
  pageNum.value = 1
  fetchUserList()
}

//新增弹窗
const userFormRef = ref(null)
const canteenTreeRef = ref(null)
const roleSelectList = ref([])
const defaultProps = {
  children: 'treeNode',
  label: 'name',
}
const addRoleDialog = ref(false)
const dialogType = ref('add')

//关联食堂勾选改变
function checkChange() {
  const checkLeafNodes = canteenTreeRef.value.getCheckedNodes(true, false)
  dataForm.value.canteenCheckNames = checkLeafNodes.map((el) => el.name).join('、')
}

function handleClose() {
  userFormRef.value.resetFields()
  canteenTreeRef.value.setCheckedKeys([])
}

const dataForm = ref({
  userId: '', //用户id用于编辑
  username: '', //用户账号
  name: '', //用户名称
  password: '', //密码
  confirmPassword: '', //确认密码
  salaryRange: [], //薪资范围
  canteenCheckNames: '', //关联食堂中文名
  areaList: [], //食堂勾选节点list
  userRoles: '',
  dutyStatus: 1,
})
//校验密码相关
import { usePasswordValidate } from '@/useHook/usePasswordValidate.js'

const { passwordState, validatePassword, checkPasswordStrength } = usePasswordValidate()
const checkConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== dataForm.value.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const roleRules = {
  username: [
    { required: true, message: '用户账号不可以为空', trigger: 'blur' },
    { required: true, message: '用户账号不可以为空', trigger: 'change' },
  ],
  name: [
    { required: true, message: '用户名称不可以为空', trigger: 'blur' },
    { required: true, message: '用户名称不可以为空', trigger: 'change' },
  ],
  password: [
    { required: true, validator: validatePassword, trigger: 'blur' },
    { required: true, validator: validatePassword, trigger: 'change' },
  ],
  confirmPassword: [
    { required: true, validator: checkConfirmPassword, trigger: 'blur' },
    { required: true, validator: checkConfirmPassword, trigger: 'change' },
  ],
  userRoles: [
    { required: true, message: '用户角色不可以为空', trigger: 'blur' },
    { required: true, message: '用户角色不可以为空', trigger: 'change' },
  ],
  // salaryRange: [
  //   {required: true, message: '薪资范围不可以为空', trigger: 'blur'},
  //   {required: true, message: '薪资范围不可以为空', trigger: 'change'}
  // ],
}

function handleFormSubmit() {
  userFormRef.value.validate((bool) => {
    if (bool) {
      const params = {
        userId: dataForm.value.userId || undefined,
        username: dataForm.value.username, //用户账号
        name: dataForm.value.name, //用户名称
        password: encryptPassword(dataForm.value.password),
        roleIdList: [dataForm.value.userRoles],
        status: dataForm.value.dutyStatus,
        companyList: dataForm.value.salaryRange, //薪资范围
        areaList: canteenTreeRef.value.getCheckedKeys(),
        t: Date.now(),
      }
      const fetchApi =
        dialogType.value === 'add' ? accessApi.saveUserInfo : accessApi.updateUserInfo
      fetchApi(params).then((res) => {
        if (res.code === 0) {
          message.success(res.msg)
          addRoleDialog.value = false
          handlePageChange(1)
        } else {
          message.warning(res.msg)
        }
      })
    }
  })
}
</script>

<style scoped lang="scss">
.role-box {
}
</style>
